<?php
namespace app\index\logic;
use app\classes\helper\Date;
use think\Db;
class Sign
{
    public function signInGoldCoin($data)
    {
        $where[]    = ['uid','=',$data['uid']];
        $where[]    = ['give_type','=',4];
        $field      = 'date';
        $orderBy    = ['id' => 'DESC'];

        $SignRecordModel  = \think\facade\App::model('UserBookPoints','model');
        $record = $SignRecordModel->getOne($where,$field,$orderBy);

        if($record && $record['date'] == $data['create_date'])
        {
            return ['code'=>102,'msg'=>'当日已签到，请勿重复签到','data'=>[]];
        }

        //判断连续签到天数
        if($record){
            $days = Date::days($record['date'], $data['create_date']);
        }else{
            $days = 1;
        }

        $UserModel = \think\facade\App::model('User', 'model');
        $info = $UserModel->getOne(['id'=>$data['uid']],'sign_days,book_coin,source_quick_id');

        $signin_days = 1;

        if($days == 1){
            //连续签到奖励初始化
            $signin_days    = isset($info['sign_days']) && $info['sign_days'] >= 1  ? $info['sign_days']+1 : 1;
        }

        $sign_rules = Db::table('quick_sign_config')->where('manage_id',request()->agentId)
                            ->field('sign_data')->findOrEmpty();

        if(empty($sign_rules))
        {
            $sign_rules = Db::table('quick_sign_config')->where('manage_id',0)
                ->field('sign_data')->findOrEmpty();
        }


        $sign_rules = json_decode($sign_rules['sign_data'],true);
        $virtual_currency = isset($sign_rules[$signin_days]) ? $sign_rules[$signin_days]['point'] : 0;
        $response['signin_days'] = $signin_days;

        $res = true;
        Db::startTrans();
        try {

            $data_u['sign_days'] = $signin_days;

            $where_u[] = ['id','=',$data['uid']];
            $UserModel->updateRecord($where_u,$data_u);

            Db::table('quick_user')->where('id',$data['uid'])->setInc('book_coin',$virtual_currency);
            Db::table('quick_user_'.intval(substr($info['source_quick_id'],-2)))->where('id',$data['uid'])->setInc('book_coin',$virtual_currency);

            $SignRecordModel->insertRecord([
                'uid'=>$data['uid'], 'continuous_days'=>$signin_days, 'date'=>$data['create_date'],
                'book_point'=>$virtual_currency, 'give_type' => 4,

            ]);

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $res = false;
            // 回滚事务
            Db::rollback();
        }

        if($res){
            return ['code'=>0,'msg'=>'success','data'=>$response];
        }else{
            return ['code'=>102,'msg'=>'签到失败','data'=>[]];
        }
    }

}